<template>
  <el-dialog :visible.sync="edit.visible" :title="title" @close="closeDialog(0)">
    <el-form ref="dataForm" :rules="edit.rules" :model="edit.temp" label-position="left" label-width="190px" style=" margin-left:3%;">
      <el-row>
        <el-col :span="24">
          <el-form-item label="计划名称:" prop="plan_name">
            <el-input v-model="edit.temp.plan_name" style="width: 90%;" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="是否并发执行:">
        <el-select v-model="edit.temp.parallel" placeholder="请选择" style="width: 90%;">
          <el-option
            v-for="item in edit.paralleljudge"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="执行时间Cron表达式:" prop="cron_express">
        <el-input v-model="edit.temp.cron_express" style="width: 90%;" />
      </el-form-item>
      <el-form-item label="执行机组:" prop="executor_group_id">
        <el-select v-model="edit.temp.executor_group_id" filterable clearable placeholder="请选择" style="width: 90%;" :disabled="edit.executorgroupdisabled" @change="executorgroupchange">
          <el-option
            v-for="item in edit.executorgroup"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="执行机:" prop="executor_id">
        <el-select v-model="edit.temp.executor_id" filterable clearable placeholder="请选择" style="width: 90%;" :disabled="edit.executordisabled" @change="executorchange">
          <el-option
            v-for="item in edit.tempexecutor"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!--动态表单-->
      <!-- 固定项目 -->
      <el-form-item label="过期时间(秒):">
        <el-input v-model="edit.temp.expire_time" style="width: 90%;" />
      </el-form-item>
      <el-form-item label="任务状态:">
        <el-select v-model="edit.temp.status" placeholder="请选择" style="width: 90%;">
          <el-option
            v-for="item in edit.statusselect"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注:" prop="mark">
        <el-input v-model="edit.temp.mark" type="textarea" style="width: 90%;" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center">
      <el-button @click="closeDialog(0)">
        取消
      </el-button>
      <el-button type="primary" @click="updateOrAddData()">
        确认提交
      </el-button>
    </div>

  </el-dialog>
</template>

<script>
import { updateOrAddList, executorgroupList, tempexecutorList } from '@/api/testplan'
export default {
  props: {// 第二种方式
    title: {
      type: String,
      default: function() {
        return ''
      }
    },
    TesltPlanItem: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    var handleCronValidate = (rule, value, callback) => {
      if (value) {
        const parser = require('cron-parser')
        try {
          const interval = parser.parseExpression(value)
          console.log('cronDate:', interval.next().toDate())
        } catch (e) {
          callback('非Cron表达式格式，请检查！' + e.message)
        }
      } else {
        callback('')
      }
      callback()
    }
    return {
      value: [{
        value: 'chrome',
        label: 'chrome'
      }, {
        value: 'ie',
        label: 'ie'
      }, {
        value: 'firefox',
        label: 'firefox'
      }],
      edit: {
        executordisabled: false,
        executorgroupdisabled: false,
        tempexecutor: [],
        testdataPlan: [],
        executorgroup: [],
        groupvalue: '',
        statusselect: [{
          value: 1,
          label: '开启'
        }, {
          value: 0,
          label: '关闭'
        }
        ],
        paralleljudge: [{
          value: 1,
          label: '是'
        }, {
          value: 0,
          label: '否'
        }
        ],
        visible: false,
        status: '',
        textMap: {
          update: '编辑计划信息',
          create: '新增计划信息',
          copy: '复制计划信息'
        },
        temp: {
          id: '',
          plan_name: '',
          parallel: 1,
          cron_express: '',
          executor_group_id: '',
          executor_id: '',
          exec_config_plan: {
            browserName: '',
            findElementTimeout: '',
            pageLoadTimeout: ''
          },
          testdata_plan: {},
          plan_key: '',
          plan_value: '',
          expire_time: '999999',
          status: 0,
          mark: ''
        },
        rules: {
          plan_name: [{ required: true, message: '请输入计划名称', trigger: 'change' }],
          // parallel: [{ required: true, message: '请选择是否并发执行', trigger: 'change' }],
          // expire_time: [{ required: true, message: '请输入过期时间(秒)', trigger: 'change' }],
          // status: [{ required: true, message: '请输入计划状态', trigger: 'change' }],
          cron_express: [{ validator: handleCronValidate, trigger: 'change' }]
        }
      }
    }
  },
  mounted() {
    const n = []
    if (this.TesltPlanItem.id !== '') {
      if (this.TesltPlanItem.executor_group_name.length > 0) {
        this.edit.executordisabled = true
      }
      if (this.TesltPlanItem.executor_name.length > 0) {
        this.edit.executorgroupdisabled = true
      }
      this.edit.temp = this.TesltPlanItem

      if (this.edit.temp.testdata_plan !== {} && this.edit.temp.testdata_plan.length !== 0) {
        for (var key in JSON.parse(this.edit.temp.testdata_plan)) {
          n.push({
            key: key,
            value: JSON.parse(this.edit.temp.testdata_plan)[key]
          })
        }
        for (var i = 0; i < n.length; i++) {
          this.edit.testdataPlan.push({
            plan_key: n[i].key,
            plan_value: n[i].value
          })
        }
      }
      this.executorgroupData()
      this.tempexecutorData()
      this.edit.visible = true
      return
    }
    this.executorgroupData()
    this.tempexecutorData()
    this.edit.visible = true
  },
  methods: {
    // 执行机组change事件
    executorgroupchange() {
      if (!this.edit.temp.executor_group_id) {
        this.reset()
        return true
      }
      this.edit.executordisabled = true
    },
    // 获取执行机
    tempexecutorData() {
      const params = {}
      tempexecutorList(params).then(response => {
        for (var i = 0; i < response.data.length; i++) {
          this.edit.tempexecutor.push({
            value: response.data[i].id,
            label: response.data[i].slave_name
          })
        }
      })
    },
    // 获取执行机组
    executorgroupData() {
      const params = {}
      executorgroupList(params).then(response => {
        // this.edit.executorgroup.id = response.data.id

        for (var i = 0; i < response.data.length; i++) {
          if (response.data[i].group_name !== '未分组') {
            this.edit.executorgroup.push({
              value: response.data[i].id,
              label: response.data[i].group_name
            })
          }
        }
      })
    },
    // 重置
    reset() {
      this.edit.temp.executor_group_id = ''
      this.edit.temp.executor_id = ''
      this.edit.executordisabled = false
      this.edit.executorgroupdisabled = false
    },
    // 动态表单
    addItem() {
      this.edit.testdataPlan.push({
        plan_key: '',
        plan_value: ''
      })
    },
    // 执行机change事件
    executorchange() {
      if (!this.edit.temp.executor_id) {
        this.reset()
        return true
      }
      this.edit.executorgroupdisabled = true
    },
    deleteItem(item, index) {
      this.edit.testdataPlan.splice(index, 1)
    },
    // 关闭弹框
    closeDialog(flag) {
      this.$refs['dataForm'].resetFields()
      this.edit.visible = false
      this.edit.executordisabled = false
      this.edit.executorgroupdisabled = false
      this.$emit('closeDialog', flag)
    },
    // 表单提交
    updateOrAddData() {
      this.$refs.dataForm.validate((validate) => {
        const n = {}
        if (validate) {
          for (var i = 0; i < this.edit.testdataPlan.length; i++) {
            n[this.edit.testdataPlan[i].plan_key] = this.edit.testdataPlan[i].plan_value
          }
          this.edit.temp.testdata_plan = JSON.stringify(n)
          this.edit.temp.exec_config_plan = JSON.stringify(this.edit.temp.exec_config_plan)

          updateOrAddList(this.edit.temp).then(response => {
            this.$message.success('提交成功')
            this.edit.visible = false
            this.closeDialog(1)
          })
        }
      })
    }
  }
}
</script>

<style scoped>
  /deep/ .jsoneditor{
    height:300px;
    left: 2%;
    margin-bottom: 20px;

  }
</style>
